<?php

class GalleryService extends FServiceBase
{
    /**
     * Get a Gallery model given its ID
     *
     * @param int id Gallery ID
     * @return FServiceModel
     */
    public function get($params)
    {
        $model = Gallery::model()->findByPk($this->getParam($params, 'id', 0));
        if (!$model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Gallery.Gallery', 'Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }

    public function save($params)
    {
        /**
         * @var CModel
         */
        $model = $this->getModel($params['Term'], 'Term');
        $this->result->processed('model', $model);

        if (!$model->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Gallery.Gallery', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly', 0) == TRUE)
            return $this->result;
        if (!$model->id)
            $model->state = Term::STATE_ACTIVE;
        if (!$model->save(false)) {
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('Gallery.Gallery', 'Error while saving submitted data into database.'));
        }

        //add/update photos to gallery
        if (isset($params['Photo']) && is_array($params['Photo']) && $model->id) {
            $ids = array();
            foreach ($params['Photo'] as $index => $item) {
                $photo = Photo::model()->findByPk(CPropertyValue::ensureInteger($item['id']));
                if (!is_object($photo))
                    $photo = new Photo;
                unset($item['id']);
                $photo->attributes = $item;
                $photo->gallery_id = $model->id;
                $photo->ordering = $index + 1;
                if (!$photo->save())
                    Yii::log(CVarDumper::dumpAsString($photo->getErrors()), CLogger::LEVEL_ERROR);
                else
                    array_push($ids, $photo->id);
            }
            //remove photos from gallery
            $criteria = new CDbCriteria;
            $criteria->compare('gallery_id', $model->id);
            $criteria->addNotInCondition('id', $ids);
            Photo::model()->deleteAll($criteria);
        }

        return $this->result;
    }


    public function delete($params)
    {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Gallery.Gallery', 'Invalid ID.'));
        }

        if (!is_array($ids)) $ids = array($ids);
        foreach ($ids as $id) {
            $model = Term::model()->findByPk($id);
            if (is_null($model)) continue;
            Photo::model()->deleteAll('gallery_id=:galleryId',array(':galleryId'=>$model->id));
            $model->delete();
        }
        return $this->result;
    }
}